<!-- Game.vue -->
<template>
  <div class="game-container" ref="gameContainer">
    <!-- 显示得分 -->
    <div class="score-board">
      Score: {{ score }}
    </div>
    <!-- 水果列表 -->
    <div
      v-for="(fruit, index) in fruits"
      :key="index"
      class="fruit"
      :style="{ top: fruit.y + 'px', left: fruit.x + 'px', width: fruit.size + 'px', height: fruit.size + 'px', backgroundColor: getFruitColor(fruit.type) }"
      @animationend="onFruitAnimationEnd(fruit)" 
    >
      {{ fruit.type }}
    </div>
    <!-- 添加水果按钮 -->
    <button class="add-fruit-btn" @click="addFruit">
      Add Fruit
    </button>
    <!-- 方向盘 -->
    <Joystick @move="handleJoystickMove" />
  </div>
</template>

<script>
import Joystick from './Joystick.vue';

export default {
  components: {
    Joystick,
  },
  data() {
    return {
      fruits: [], // 存储所有水果
      nextFruitType: "🍎", // 默认水果类型
      nextFruitSize: 40, // 默认水果大小
      fallInterval: null, // 下落定时器
      containerHeight: 600, // 容器高度
      containerWidth: 800, // 容器宽度
      score: 0, // 玩家得分
    };
  },
  methods: {
    // 添加新水果
    addFruit() {
      if (this.fruits.every(fruit => !fruit.falling)) {
        const newFruit = {
          type: this.nextFruitType,
          size: this.nextFruitSize,
          x: Math.random() * (this.containerWidth - this.nextFruitSize),
          y: 0,
          speed: 2,
          falling: true,
          isMovable: true, // 设置为可移动
        };
        this.fruits.push(newFruit);

        // 开始下落逻辑
        this.startFalling();
      }
    },
  
    // 开始下落
    startFalling() {
      if (this.fallInterval) {
        clearInterval(this.fallInterval);
      }
      this.fallInterval = setInterval(() => {
        let allStopped = true;
        this.fruits.forEach((fruit) => {
          if (fruit.falling) {
            fruit.y += fruit.speed;
            if (fruit.y + fruit.size > this.containerHeight) {
              fruit.falling = false; // 到达底部后停止下落
            } else {
              allStopped = false;
            }
          }
        });
        this.checkCollisions();

        if (allStopped) {
          clearInterval(this.fallInterval);
          this.fallInterval = null;
        }
      }, 16);
    },
  
    // 停止下落
    stopFalling() {
      if (this.fallInterval) {
        clearInterval(this.fallInterval);
        this.fallInterval = null;
      }
    },
  
    // 碰撞检测与合成
    checkCollisions() {
      for (let i = 0; i < this.fruits.length; i++) {
        for (let j = i + 1; j < this.fruits.length; j++) {
          const fruit1 = this.fruits[i];
          const fruit2 = this.fruits[j];

          if (
            fruit1.x < fruit2.x + fruit2.size &&
            fruit1.x + fruit1.size > fruit2.x &&
            fruit1.y < fruit2.y + fruit2.size &&
            fruit1.y + fruit1.size > fruit2.y
          ) {
            this.combineFruits(i, j);
            return; // 一次只处理一次碰撞
          }
        }
      }
    },
  
    // 合并水果
    combineFruits(i, j) {
      const fruit1 = this.fruits[i];
      const fruit2 = this.fruits[j];

      const newSize = Math.min(fruit1.size + fruit2.size, 100);
      const newX = Math.min(fruit1.x, fruit2.x);
      const newY = this.containerHeight - newSize; // 设置合成后水果的 y 坐标为容器底部

      // 计算得分：水果大小每增加10px，加1分
      const scoreIncrement = Math.floor((newSize - fruit1.size - fruit2.size + Math.min(fruit1.size, fruit2.size)) / 10);
      const combinedScore = 10; // 每次合并加10分

      const combinedFruit = {
        type: "🍎🍎", // 合成后的类型
        size: newSize,
        x: newX,
        y: newY,
        speed: 0,
        falling: false,
        isMovable: false, // 设置为不可移动
      };

      // 替换水果
      this.fruits.splice(j, 1);
      this.fruits.splice(i, 1);
      this.fruits.push(combinedFruit);

      // 更新得分
      this.score += combinedScore;
    },
  
    // 获取水果颜色
    getFruitColor(type) {
      const colors = {
        "🍎": "#ff6b6b",
        "🍌": "#ffe66d",
        "🍇": "#8e44ad",
      };
      return colors[type] || "#ccc";
    },
  
    // 动画结束事件（可用于扩展）
    onFruitAnimationEnd(fruit) {
      // 可添加合成成功动画逻辑
    },
  
    // 处理方向盘移动
    handleJoystickMove(direction) {
      this.fruits.forEach((fruit) => {
        if (fruit.isMovable !== false) { // 只处理可移动的水果
          const step = 10; // 移动步长

          // 更新水果位置（只处理水平移动）
          fruit.x = Math.max(0, Math.min(this.containerWidth - fruit.size, fruit.x + direction.x * step));

          // 如果水果到达底部，停止下落
          if (fruit.y + fruit.size >= this.containerHeight) {
            fruit.falling = false;
          }
        }
      });
    },
  },
  mounted() {
    // window.addEventListener('keydown', this.handleKeyDown); // 移除键盘事件监听
  },
  beforeUnmount() {
    this.stopFalling();
    // window.removeEventListener('keydown', this.handleKeyDown); // 移除键盘事件监听
  },
};
</script>

<style scoped>
/* 容器样式 */
.game-container {
  position: relative;
  width: 100%;
  max-width: 800px;
  height: 600px;
  margin: 50px auto;
  border: 5px solid #4caf50;
  border-radius: 20px;
  overflow: hidden;
  background: linear-gradient(135deg, #f0f9ff, #cbebff);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.2);
}

/* 分数板样式 */
.score-board {
  position: absolute;
  top: 10px;
  left: 10px;
  font-size: 24px;
  font-weight: bold;
  color: #4caf50;
  text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.5);
}

/* 水果样式 */
.fruit {
  position: absolute;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 50%;
  font-size: 20px;
  font-weight: bold;
  color: white;
  text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.5);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
  animation: fall 0.5s ease-out; /* 下落动画 */
}

.fruit:hover {
  transform: scale(1.1);
  box-shadow: 0 6px 12px rgba(0, 0, 0, 0.3);
}

/* 按钮样式 */
.add-fruit-btn {
  display: block;
  margin: 20px auto;
  padding: 10px 20px;
  font-size: 18px;
  color: white;
  background: linear-gradient(135deg, #4caf50, #388e3c);
  border: none;
  border-radius: 5px;
  cursor: pointer;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.2);
  transition: background-color 0.3s ease, transform 0.2s ease;
}

.add-fruit-btn:hover {
  background: linear-gradient(135deg, #388e3c, #2e7d32);
  transform: scale(1.05);
}

.add-fruit-btn:active {
  transform: scale(0.95);
}

/* 动画效果 */
@keyframes fall {
  from {
    transform: translateY(-100%);
    opacity: 0;
  }
  to {
    transform: translateY(0);
    opacity: 1;
  }
}
</style>